package cn.kongwg.json;

import cn.kongwg.pojo.Person;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kongwg
 * @create 2021-01-31 17:03
 */
public class JsonTojava {

    @Test
    public void JsonBean(){
        Person p = new Person(1,"微光");
        Gson gson = new Gson();

        String s = gson.toJson(p);
        System.out.println(s);

        Person person = gson.fromJson(s, Person.class);
        System.out.println(person);
    }

    @Test
    public void testJsonList(){
        List<Person> list = new ArrayList<>();

        list.add(new Person(1, "靓仔"));
        list.add(new Person(2, "帅逼"));

        Gson gson = new Gson();
        String s = gson.toJson(list);
        System.out.println(s);

//        List<Person> per= gson.fromJson(s, new PersonType().getType());
        List<Person> per = gson.fromJson(s, new TypeToken<ArrayList<Person>>() {
        }.getType());
        Person person = per.get(0);
        System.out.println(person);
    }

    @Test
    public void testJsonMap(){
        Map<Integer,Person> map = new HashMap<>();

        map.put(1,new Person(1, "靓仔"));
        map.put(2,new Person(2, "微光"));

        Gson gson = new Gson();
        String s = gson.toJson(map);

        System.out.println(s);

        Map<Integer, Person> per = gson.fromJson(s, new TypeToken<HashMap<Integer, Person>>() {
        }.getType());

        System.out.println(per);
        Person person = per.get(1);
        System.out.println(person);
    }
}
